<?php
/**
 * WooCommerce Ajax Handlers
 * WooCommerce Ajax处理器
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * Ajax添加到购物车
 */
function wbw_ajax_add_to_cart() {
    // 验证nonce
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $product_id = absint($_POST['product_id']);
    $quantity = !empty($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1;
    $variation_id = absint($_POST['variation_id'] ?? 0);
    $variation = $_POST['variation'] ?? array();

    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variation) && 'publish' === $product_status) {
        do_action('woocommerce_ajax_added_to_cart', $product_id);

        if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
            wc_add_to_cart_message(array($product_id => $quantity), true);
        }

        WC_AJAX::get_refreshed_fragments();
    } else {
        $data = array(
            'error' => true,
            'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)
        );

        wp_send_json($data);
    }
}
add_action('wp_ajax_wbw_add_to_cart', 'wbw_ajax_add_to_cart');
add_action('wp_ajax_nopriv_wbw_add_to_cart', 'wbw_ajax_add_to_cart');

/**
 * Ajax移除购物车商品
 */
function wbw_ajax_remove_cart_item() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
    
    if (WC()->cart->remove_cart_item($cart_item_key)) {
        $cart_count = WC()->cart->get_cart_contents_count();
        wp_send_json_success(array(
            'cart_count' => $cart_count,
            'message' => 'Item removed from cart'
        ));
    } else {
        wp_send_json_error(array('message' => 'Failed to remove item'));
    }
}
add_action('wp_ajax_wbw_remove_cart_item', 'wbw_ajax_remove_cart_item');
add_action('wp_ajax_nopriv_wbw_remove_cart_item', 'wbw_ajax_remove_cart_item');

/**
 * Ajax更新购物车数量
 */
function wbw_ajax_update_cart_quantity() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $cart_item_key = sanitize_text_field($_POST['cart_item_key']);
    $quantity = wc_stock_amount($_POST['quantity']);
    
    if (WC()->cart->set_quantity($cart_item_key, $quantity)) {
        $cart_count = WC()->cart->get_cart_contents_count();
        $cart_total = WC()->cart->get_cart_total();
        
        wp_send_json_success(array(
            'cart_count' => $cart_count,
            'cart_total' => $cart_total,
            'message' => 'Cart updated'
        ));
    } else {
        wp_send_json_error(array('message' => 'Failed to update cart'));
    }
}
add_action('wp_ajax_wbw_update_cart_quantity', 'wbw_ajax_update_cart_quantity');
add_action('wp_ajax_nopriv_wbw_update_cart_quantity', 'wbw_ajax_update_cart_quantity');

/**
 * Ajax愿望清单功能
 */
function wbw_ajax_add_to_wishlist() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    if (!is_user_logged_in()) {
        wp_send_json_error(array('message' => 'Please login to add to wishlist'));
    }

    $product_id = absint($_POST['product_id']);
    $user_id = get_current_user_id();
    $wishlist = get_user_meta($user_id, 'wbw_wishlist', true);
    
    if (!is_array($wishlist)) {
        $wishlist = array();
    }

    if (!in_array($product_id, $wishlist)) {
        $wishlist[] = $product_id;
        update_user_meta($user_id, 'wbw_wishlist', $wishlist);
        
        wp_send_json_success(array(
            'wishlist_count' => count($wishlist),
            'message' => 'Added to wishlist'
        ));
    } else {
        wp_send_json_error(array('message' => 'Already in wishlist'));
    }
}
add_action('wp_ajax_wbw_add_to_wishlist', 'wbw_ajax_add_to_wishlist');

/**
 * Ajax从愿望清单移除
 */
function wbw_ajax_remove_from_wishlist() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    if (!is_user_logged_in()) {
        wp_send_json_error(array('message' => 'Please login first'));
    }

    $product_id = absint($_POST['product_id']);
    $user_id = get_current_user_id();
    $wishlist = get_user_meta($user_id, 'wbw_wishlist', true);
    
    if (!is_array($wishlist)) {
        $wishlist = array();
    }

    $key = array_search($product_id, $wishlist);
    if ($key !== false) {
        unset($wishlist[$key]);
        update_user_meta($user_id, 'wbw_wishlist', array_values($wishlist));
        
        wp_send_json_success(array(
            'wishlist_count' => count($wishlist),
            'message' => 'Removed from wishlist'
        ));
    } else {
        wp_send_json_error(array('message' => 'Product not in wishlist'));
    }
}
add_action('wp_ajax_wbw_remove_from_wishlist', 'wbw_ajax_remove_from_wishlist');

/**
 * Ajax比较功能
 */
function wbw_ajax_add_to_compare() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $product_id = absint($_POST['product_id']);
    $compare_list = isset($_COOKIE['wbw_compare']) ? json_decode(stripslashes($_COOKIE['wbw_compare']), true) : array();
    
    if (!is_array($compare_list)) {
        $compare_list = array();
    }

    if (count($compare_list) >= 4) {
        wp_send_json_error(array('message' => 'You can compare maximum 4 products'));
    }

    if (!in_array($product_id, $compare_list)) {
        $compare_list[] = $product_id;
        setcookie('wbw_compare', json_encode($compare_list), time() + (86400 * 30), '/');
        
        wp_send_json_success(array(
            'compare_count' => count($compare_list),
            'message' => 'Added to compare list'
        ));
    } else {
        wp_send_json_error(array('message' => 'Already in compare list'));
    }
}
add_action('wp_ajax_wbw_add_to_compare', 'wbw_ajax_add_to_compare');
add_action('wp_ajax_nopriv_wbw_add_to_compare', 'wbw_ajax_add_to_compare');

/**
 * Ajax快速查看
 */
function wbw_ajax_quick_view() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $product_id = absint($_POST['product_id']);
    $product = wc_get_product($product_id);
    
    if (!$product) {
        wp_send_json_error(array('message' => 'Product not found'));
    }

    // 构建快速查看HTML
    ob_start();
    ?>
    <div class="quick-view-content">
        <div class="row">
            <div class="col-md-6">
                <div class="product-images">
                    <?php echo $product->get_image('medium'); ?>
                </div>
            </div>
            <div class="col-md-6">
                <div class="product-details">
                    <h3><?php echo $product->get_name(); ?></h3>
                    <div class="price"><?php echo $product->get_price_html(); ?></div>
                    <div class="description">
                        <?php echo wp_trim_words($product->get_short_description(), 20); ?>
                    </div>
                    
                    <?php if ($product->is_type('simple')) : ?>
                        <form class="cart" method="post" enctype="multipart/form-data">
                            <div class="quantity">
                                <input type="number" name="quantity" value="1" min="1" max="<?php echo $product->get_stock_quantity(); ?>" step="1">
                            </div>
                            <button type="submit" class="btn-add-cart ajax_add_to_cart" data-product_id="<?php echo $product_id; ?>">
                                Add to Cart
                            </button>
                        </form>
                    <?php endif; ?>
                    
                    <div class="product-actions">
                        <button class="btn-wishlist" data-product-id="<?php echo $product_id; ?>">
                            <i class="feather-heart"></i> Wishlist
                        </button>
                        <button class="btn-compare" data-product-id="<?php echo $product_id; ?>">
                            <i class="feather-shuffle"></i> Compare
                        </button>
                    </div>
                    
                    <a href="<?php echo get_permalink($product_id); ?>" class="btn-view-details">
                        View Full Details
                    </a>
                </div>
            </div>
        </div>
    </div>
    <?php
    $html = ob_get_clean();
    
    wp_send_json_success(array('html' => $html));
}
add_action('wp_ajax_wbw_quick_view', 'wbw_ajax_quick_view');
add_action('wp_ajax_nopriv_wbw_quick_view', 'wbw_ajax_quick_view');

/**
 * Ajax获取变体价格
 */
function wbw_ajax_get_variation_price() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $product_id = absint($_POST['product_id']);
    $variation_id = absint($_POST['variation_id']);
    
    if ($variation_id) {
        $variation = wc_get_product($variation_id);
        if ($variation) {
            wp_send_json_success(array(
                'price_html' => $variation->get_price_html(),
                'availability_html' => wc_get_stock_html($variation)
            ));
        }
    }
    
    wp_send_json_error();
}
add_action('wp_ajax_wbw_get_variation_price', 'wbw_ajax_get_variation_price');
add_action('wp_ajax_nopriv_wbw_get_variation_price', 'wbw_ajax_get_variation_price');

/**
 * Ajax产品筛选
 */
function wbw_ajax_filter_products() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $orderby = sanitize_text_field($_POST['orderby'] ?? 'menu_order');
    $order = sanitize_text_field($_POST['order'] ?? 'ASC');
    $meta_query = array();
    $tax_query = array();
    
    // 价格筛选
    if (!empty($_POST['min_price']) || !empty($_POST['max_price'])) {
        $meta_query[] = array(
            'key' => '_price',
            'value' => array(
                floatval($_POST['min_price'] ?? 0),
                floatval($_POST['max_price'] ?? 999999)
            ),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC'
        );
    }
    
    // 分类筛选
    if (!empty($_POST['categories'])) {
        $categories = array_map('absint', $_POST['categories']);
        $tax_query[] = array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => $categories
        );
    }
    
    // 属性筛选
    if (!empty($_POST['attributes'])) {
        foreach ($_POST['attributes'] as $taxonomy => $terms) {
            $tax_query[] = array(
                'taxonomy' => sanitize_text_field($taxonomy),
                'field' => 'slug',
                'terms' => array_map('sanitize_text_field', $terms)
            );
        }
    }

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'posts_per_page' => 12,
        'paged' => absint($_POST['page'] ?? 1),
        'orderby' => $orderby,
        'order' => $order,
        'meta_query' => $meta_query,
        'tax_query' => $tax_query
    );

    $query = new WP_Query($args);
    
    ob_start();
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            wc_get_template_part('content', 'product');
        }
    } else {
        echo '<p>No products found.</p>';
    }
    wp_reset_postdata();
    
    $html = ob_get_clean();
    
    wp_send_json_success(array(
        'html' => $html,
        'found_posts' => $query->found_posts,
        'max_pages' => $query->max_num_pages
    ));
}
add_action('wp_ajax_wbw_filter_products', 'wbw_ajax_filter_products');
add_action('wp_ajax_nopriv_wbw_filter_products', 'wbw_ajax_filter_products');

/**
 * Ajax搜索建议
 */
function wbw_ajax_search_suggestions() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $search_term = sanitize_text_field($_POST['search_term']);
    
    if (strlen($search_term) < 2) {
        wp_send_json_error();
    }

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        's' => $search_term,
        'posts_per_page' => 5
    );

    $query = new WP_Query($args);
    $suggestions = array();
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $product = wc_get_product();
            $suggestions[] = array(
                'id' => get_the_ID(),
                'title' => get_the_title(),
                'url' => get_permalink(),
                'price' => $product->get_price_html(),
                'image' => get_the_post_thumbnail_url(get_the_ID(), 'thumbnail')
            );
        }
    }
    wp_reset_postdata();
    
    wp_send_json_success($suggestions);
}
add_action('wp_ajax_wbw_search_suggestions', 'wbw_ajax_search_suggestions');
add_action('wp_ajax_nopriv_wbw_search_suggestions', 'wbw_ajax_search_suggestions');

/**
 * Ajax获取比较产品信息
 */
function wbw_ajax_get_compare_products() {
    if (!wp_verify_nonce($_POST['nonce'], 'wbw_ajax_nonce')) {
        wp_die('Security check failed');
    }

    $product_ids = array_map('absint', $_POST['product_ids']);
    $products = array();
    
    foreach ($product_ids as $product_id) {
        $product = wc_get_product($product_id);
        if ($product) {
            $products[] = array(
                'id' => $product_id,
                'name' => $product->get_name(),
                'price' => $product->get_price_html(),
                'image' => get_the_post_thumbnail_url($product_id, 'thumbnail'),
                'url' => get_permalink($product_id)
            );
        }
    }
    
    wp_send_json_success($products);
}
add_action('wp_ajax_wbw_get_compare_products', 'wbw_ajax_get_compare_products');
add_action('wp_ajax_nopriv_wbw_get_compare_products', 'wbw_ajax_get_compare_products');